from flask import Blueprint, request, abort
from flask_restful import reqparse, inputs, Resource, Api, fields, marshal_with
from ....models.database import db, auto_commit
from ....decorator.consolejwt import console_token
from ...res import output_json
from ....models.console.section import Section
from ....models.console.admin import Admin
from ....libs.unit import abort_msg


# 蓝图并放入 restful
section = Blueprint('section', __name__, url_prefix='/c-api/section')
api = Api(section)

# 统一封装 API 返回值
@api.representation('application/json')
def out_json(data, code, headers=None):
    return output_json(data, code, headers=None)


# 封装返回的数据格式
resource_list = {
    'count': fields.Integer,
    'list': fields.List(fields.Nested({
        'id': fields.Integer,
        'name': fields.String,
        'status': fields.String
    }))
}


class ListSection(Resource):
    @console_token
    @marshal_with(resource_list, envelope='resource')
    def get(self):
        # 请求验证
        parser = reqparse.RequestParser()
        parser.add_argument('page', type=int,
                            help='页码必须填写', location=['form', 'args'], required=True, action='store')
        args = parser.parse_args()
        page = args.get('page')
        with auto_commit():
            lists = Section.query.order_by(Section.id.desc()).paginate(
                page, per_page=10, error_out=False)
            c = {'count': lists.total, 'list': lists.items}
        return c


# 封装返回的数据格式
resource_detail = {
    'id': fields.Integer,
    'name': fields.String,
    'status': fields.String
}
class DetailSection(Resource):
    @console_token
    @marshal_with(resource_detail, envelope='resource')
    def get(self):
        # 请求验证
        parser = reqparse.RequestParser()
        parser.add_argument('section_id', type=int,
                            help='部门 ID 必须填写', location=['form', 'args'], required=True, action='store')
        args = parser.parse_args()
        with auto_commit():
            c = Section.query.filter(Section.id == args.get('section_id')).one()
        return c 


class CreateSection(Resource):
    @console_token
    def post(self):
        # 请求验证
        parser = reqparse.RequestParser()
        parser.add_argument('name', type=str,
                            help='部门名称必须填写', location=['form', 'args'], required=True, action='store')
        parser.add_argument('status', type=inputs.positive,
                            help='状态标识必须填写', location=['form', 'args'], required=False, action='store', default=1)
        args = parser.parse_args()
        with auto_commit():
            c = Section()
            c.name = args.get('name')
            c.display = args.get('status')
            db.session.add(c)
        return {'resource': ''}


class EditSection(Resource):
    @console_token
    def  put(self):
        # 请求验证
        parser = reqparse.RequestParser()
        parser.add_argument('section_id', type=inputs.positive,
                            help='部门 ID 必须填写', location=['form', 'args'], required=True, action='store')
        parser.add_argument('name', type=str,
                            help='部门名称必须填写', location=['form', 'args'], required=True, action='store')
        parser.add_argument('status', type=inputs.positive,
                            help='状态标识必须填写', location=['form', 'args'], required=False, action='store', default=1)
        args = parser.parse_args()
        with auto_commit():
            c = Section.query.filter(Section.id == args.get('section_id')).one()
            c.name = args.get('name')
            c.display = args.get('status')
        return {'resource': ''}


class DeleteSection(Resource):
    @console_token
    def delete(self):
        # 请求验证
        parser = reqparse.RequestParser()
        parser.add_argument('section_id', type=inputs.positive,
                            help='部门 ID 必须填写', location=['form', 'args'], required=True, action='store')
        args = parser.parse_args()
        with auto_commit():
            # 先查有没有用户
            c = Admin.query.filter(Admin.section_id == args.get('section_id')).count()
            if c > 0:
                abort(401, '部门下有用户，请先给用户修改部门')
            Section.query.filter(Section.id == args.get('section_id')).delete()
            db.session.flush()
        return {'resource': ''}
        
api.add_resource(ListSection, '/list')
api.add_resource(DetailSection, '/detail')
api.add_resource(CreateSection, '/create')
api.add_resource(EditSection, '/edit')
api.add_resource(DeleteSection, '/delete')
